<template>
  <div>
    <div class="screen">
      <!-- 筛选 -->

      <div class="screen_content">
        <div class="screen_content_first">
          <i class="el-icon-search">筛选搜索</i>
          <div class="screen_content_first_btutton"></div>
        </div>
        <div class="screen_content_second">
          <div class="screen_content_second_one">
            <div style="width:150px">投票标题:</div>
            <el-input
              v-model="Rule_name"
              placeholder="请输入规则标题"
              clearable
              @clear="clearclick()"
            ></el-input>
            <el-button
              style="margin-left:10px;"
              @click="Search()"
              type="primary"
              >查询搜索</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <div class="tables">
      <!-- 表格 -->
      <el-table
        fit
        border
        :data="
          tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)
        "
        :header-cell-style="headerclass"
        align:center
        style="width: 100%"
      >
        <el-table-column align="center" label="编号">
          <template slot-scope="scope">{{ scope.$index }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="title"
          label="投票标题"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          prop="describe"
          label="投票描述"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="截止时间" width="200px">
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.endtime | timeF }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="发布时间" width="200px">
          <template slot-scope="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.createtime | timeF }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="投票状态" fixed="right">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status">投票中</el-tag>
            <el-tag v-else type="warning">待审核</el-tag>
            <el-tag
              v-if="new Date(scope.row.endtime) > new Date()"
              type="success"
              >进行中</el-tag
            >
            <el-tag v-if="new Date(scope.row.endtime) < new Date()" type="info"
              >已结束</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              @click="checkClick(scope.row)"
              type="success"
              plain
              size="mini"
              >查看投票</el-button
            >
            <el-button
              @click="deleteClick(scope.row)"
              type="danger"
              plain
              size="mini"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
        ></el-pagination>
      </div>
    </div>
    <el-dialog :visible.sync="isShown">
      <el-form :model="rows">
        <el-form-item
          class="el-form-item"
          label="投票标题"
          :label-width="formLabelWidth"
        >
          {{ rows.title }}
        </el-form-item>
        <el-form-item
          class="el-form-item"
          label="投票描述"
          :label-width="formLabelWidth"
        >
          {{ rows.describe }}
        </el-form-item>
        <el-form-item
          class="el-form-item"
          label="投票主图"
          :label-width="formLabelWidth"
        >
          <img
            style="width:100px"
            :src="Voting_img_prefix + rows.images"
            v-if="rows.images"
          />
          <div v-else>无主图</div>
        </el-form-item>
        <el-form-item
          class="el-form-item"
          label="投票总次数"
          :label-width="formLabelWidth"
        >
          {{ rows.voteNum }}
        </el-form-item>
        <el-form-item
          class="el-form-item"
          label="每人可投票次数"
          :label-width="formLabelWidth"
        >
          {{ rows.selectNum }}
        </el-form-item>
        <el-form-item
          class="el-form-item"
          label="截止时间"
          :label-width="formLabelWidth"
        >
          {{ rows.endtime | timeF }}
        </el-form-item>
        <el-form-item
          class="el-form-item"
          label="投票情况"
          :label-width="formLabelWidth"
        >
          <div v-for="(item, index) in rows.option" :key="index">
            <div class="flexcontents1">选项{{ index + 1 }}</div>
            <div class="flexs">
              <div class="flexcontents2" v-if="item.optionfile">
                <img
                  style="width:200px"
                  :src="Voting_img_prefix + item.optionfile"
                />
              </div>
              <div cllass="flexcontents2" v-if="item.optionvideo">
                视频链接：<el-link :href="item.optionvideo" target="primary">{{
                  item.optionvideo
                }}</el-link>
              </div>
              <div class="flexcontents3">选项标题：{{ item.optiontitle }}</div>
              <div class="flexcontents4">被投票数：{{ item.optionnum }}</div>
              <div class="flexcontents5" v-if="rows.voteNum > 0">
                占比值：{{
                  ((item.optionnum / rows.voteNum) * 100).toFixed(2)
                }}%
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          class="el-form-item"
          label="目前投票数最多"
          :label-width="formLabelWidth"
        >
          {{ sum }}
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getvotelist, putvotelist, PUT_VOTE_IMG } from "@/api/votepc";
import Vue from "vue";
import VueDirectiveImagePreviewer from "vue-directive-image-previewer";
import "vue-directive-image-previewer/dist/assets/style.css";
Vue.use(VueDirectiveImagePreviewer);
import { Voting_img_prefix } from "@/utils/global";
import { formatDateTime } from "../../../common/Time";

export default {
  name: "vote",
  watch: {
    async $route() {
      //监听路由是否变化
      if (this.$route.path == "/personalCenter") {
        this.getdata();
      }
    }
  },
  data() {
    return {
      formLabelWidth: "120px",
      Voting_img_prefix: Voting_img_prefix,
      rows: { option: [] },
      isShown: false, //弹窗开关
      Rule_name: "", //搜索规则标题
      tableData: [], // 表格数据
      tableData1: [], // 表格数据
      pagesize: 10, //分页显示多少条数据
      currentPage: 1 //分页默认第几个页面
    };
  },
  created() {
    this.getdata();
  },
  filters: {
    timeF(val) {
      return formatDateTime(Date.parse(val));
    }
  },
  computed: {
    // 计算属性的 getter
    sum: function() {
      // `this` 指向 vm 实例
      if (this.rows.option) {
        var list = new Array();
        for (var i in this.rows.option) {
          list.push(this.rows.option[i].optionnum);
        }
        list.sort(function(num1, num2) {
          return num1 - num2;
        });
        var maxcnt = eval(list[list.length - 1]);
        return maxcnt;
      } else {
        return "无";
      }
    }
  },
  methods: {
    async getdata() {
      try {
        getvotelist({
          query: { Creat_people: this.$store.getters.userInfo._id },
          sort: { _id: "-1" }
        }).then(response => {
          this.tableData1 = response.data;
          this.tableData = this.tableData1;
          console.log(this.tableData);
        });
      } catch (e) {
        this.$message.error("请求失败，请重新刷新或返回上一页");
      }
    },
    changeClick1(data) {
      console.log(data);
      var datas = {
        query: { _id: data._id },
        update: {
          $set: {
            status: !data.status
          }
        }
      };

      putvotelist(datas).then(response => {
        if (
          response.data.n == 1 &&
          response.data.nModified == 1 &&
          response.data.ok == 1
        ) {
          this.$notify({
            title: "已修改投票状态",
            message: "以将" + data.title + "状态改变",
            type: "success",
            duration: 2000
          });
          this.getdata();
        } else {
          this.$notify({
            title: "修改失败，请重试或刷新",
            message: "未将" + data.title + "状态改变",
            type: "danger",
            duration: 2000
          });
        }
      });
    },
    clearclick() {
      this.tableData = this.tableData1;
    },
    //搜索按钮事件
    Search() {
      if (this.Rule_name) {
        var datas = this.searchByIndexOf(this.Rule_name, this.tableData1);
        this.tableData = datas;
      } else {
        this.tableData = this.tableData1;
      }
    },
    //模糊查询1:利用字符串的indexOf方法
    searchByIndexOf(keyWord, list) {
      if (!(list instanceof Array)) {
        return;
      }
      var len = list.length;
      var arr = [];

      for (var i = 0; i < len; i++) {
        //如果字符串中不包含目标字符会返回-1
        if (list[i].title.indexOf(keyWord) >= 0) {
          arr.push(list[i]);
        }
      }
      return arr;
    },
    //编辑内容
    handleClick1(num) {
      this.$router.push({
        name: "rule_adit",
        params: {
          id: num
        }
      });
    },
    //查看事件
    aditClick(row) {
      this.htmls = row.Rule_message;
      if (this.isShown) {
        this.isShown = false;
      } else {
        this.isShown = true;
      }
    },
    //添加事件
    handleClick() {
      // var num = this.tableData;
      this.$router.push({
        name: "vote_adit",
        params: {
          onif: "添加"
        }
      });
    },
    checkClick(row) {
      this.rows = row;
      this.isShown = true;
    },
    //删除事件
    deleteClick(num) {
      var that = this;
      that
        .$confirm("确认删除吗？")
        .then(async () => {
          console.log(num);
          var a = await PUT_VOTE_IMG(num);
          console.log(a);
          if (a.code == 200) {
            this.$notify({
              title: "已删除成功",
              message: "以将" + num.title + "删除",
              type: "success",
              duration: 2000
            });
            this.getdata();
          }
        })
        .catch(() => {});
    },
    //表格表头的样式
    headerclass() {
      return "background:#f2f6fc;color:#505050;font-weight:500;text-align: center;";
    },
    //分页--初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function(size) {
      this.pagesize = size; //每页下拉显示数据
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage; //点击第几页
    }
  }
};
</script>

<style lang="scss">
.screen {
  margin: 2vw;
  width: 100%;
  border: 1px solid #ebeef5;
  border-radius: 5px;
}
.screen1 {
  margin: 0 2vw 0 2vw;
  width: 96%;
  border: 1px solid #ebeef5;
  border-radius: 5px;
}
.screen_content {
  display: flex;
  flex-direction: column;
}
.screen_content_first {
  width: 100%;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
}

.el-icon-search {
  padding: 8px;
}
.el-icon-tickets {
  line-height: 30px;
}
.screen_content_second {
  width: 100%;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}
.screen_content_second_one {
  padding: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.tables {
  margin: 1vw 2vw 1vw 2vw;
  width: 100%;
  border-radius: 5px;
}
.block {
  margin: 2vw;
  display: flex;
  flex-direction: row-reverse;
  flex-wrap: wrap;
}
.fordatas {
  display: flex;
  flex-direction: column;
  align-items: baseline;
}
.el-tag {
  margin-bottom: 5px;
}
.flexcontents1 {
  font-size: 15px;
  font-weight: 600;
  color: #000;
}
.flexs {
  display: flex;
  flex-direction: column;
}
.el-form-item {
  width: auto !important;
  justify-content: flex-start !important;
}
</style>
